/* 
 *   Classname:  config.WebJarsController
 * 
 *   Date       Developer   Description
 *   2018年3月12日    周成功              新建
 *
 */
package SpringBoot.__template.full.config;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerMapping;
import org.webjars.WebJarAssetLocator;

import com.titan.core.utils.io.ConsoleUtils;

/**
 *
 *
 * @author 周成功
 *
 */
@Controller
public class WebResourceController {
    private final WebJarAssetLocator assetLocator = new WebJarAssetLocator();
    private final static Map<String,String> cache = new HashMap<String,String>();
    static {
        cache.put("/WebResource/jquery/js", "META-INF/resources/webjars/jquery/3.3.1-1/jquery.min.js");
        cache.put("/WebResource/bootstrap/js", "META-INF/resources/webjars/bootstrap/3.3.7-1/js/bootstrap.min.js");
        cache.put("/WebResource/bootstrap/css", "META-INF/resources/webjars/bootstrap/3.3.7-1/css/bootstrap.min.css");
        cache.put("/WebResource/titan/js", "META-INF/resources/webjars/Common56/v2.0/js/common_base.js");
        cache.put("/WebResource/titan/css", "META-INF/resources/webjars/Common56/v2.0/style/common_base.css");
    }
    
    
    @ResponseBody
    @RequestMapping("/WebResource/{webjar}/**")
    public ResponseEntity<Object> locateWebjarAsset(@PathVariable String webjar, HttpServletRequest request) {
        try {
//            ConsoleUtils.log("locateWebjarAsset", "webjar", webjar);
//            String mvcPrefix = "/WebResource/" + webjar + "/"; // This prefix must match the mapping path!
//            ConsoleUtils.log("locateWebjarAsset", "mvcPrefix", mvcPrefix);
//            String mvcPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
//            ConsoleUtils.log("locateWebjarAsset", "mvcPath", mvcPath);
//            String fullPath = assetLocator.getFullPath(webjar+"/3.3.1-1", mvcPath.substring(mvcPrefix.length()));
//            ConsoleUtils.log("locateWebjarAsset", "fullPath", fullPath);
            
            String mvcPath = (String)request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
            String fullPath = cache.get(mvcPath);
            return new ResponseEntity<>(new ClassPathResource(fullPath), HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
}
